/*
 * KKEvent.cpp
 *
 *  Created on: 2013-9-15
 *      Author: wanghua
 */

#include "KKEvent.h"
#include "KKDirector.h"

USING_NS_CC;

KKEvent::KKEvent() {
	m_actions = new KKEventActionArray();

	m_eventHandler = NULL;
}

KKEvent::~KKEvent() {
	CC_SAFE_DELETE(this->m_actions);
	CC_SAFE_DELETE(this->m_eventHandler);
}

KKEvent* KKEvent::eventWithXml(TiXmlElement* element) {
	KKEvent* event = new KKEvent();

	if (event->initWithXml(element)) {
		event->retain();
		event->autorelease();
		return event;
	}

	CC_SAFE_DELETE(event);

	return NULL;
}

bool KKEvent::initWithXml(TiXmlElement* element) {

	this->m_name = element->Attribute("name");

	TiXmlElement* actionElment = element->FirstChildElement("action");

	while (actionElment) {

		KKEventAction* action = KKEventAction::actionWithXml(actionElment);

		if (action) {
			this->m_actions->addObject(action);
		}

		actionElment = actionElment->NextSiblingElement("action");
	}

	return this->m_actions->count() > 0;
}

void KKEvent::fire(KKEventActionArgs* args) {

	if (m_eventHandler) {
		CCNode* ccTarget = NULL; //dynamic_cast<CCNode*>(m_eventHandler->target);

		if (ccTarget == NULL) {
			ccTarget = dynamic_cast<CCNode*>((KKNode*) args->getSource());
		}
		m_eventHandler->handle(ccTarget, args);
	}

	KKEventActionArray::CCMutableArrayIterator it = this->m_actions->begin();

	KKEventAction* action = NULL;

	while (it != this->m_actions->end()) {
		action = (KKEventAction*) (*it);

		if (KKDirector::isDebug) {
			CCLog("begin fire %s -> %s \n", action->getTarget(),
					action->getAction());
		}

		action->run(args);

		it++;
	}
}
